# -*- coding: utf-8 -*-
# @File  : 进程锁.py
# @Author: zbh
# @Date  : 2025/2/24_15:54


'''需要注意的是，被阻塞的进程只是无法进入受锁保护的关键代码段，它仍然可以执行其他不受该锁影响的代码。'''

import multiprocessing
import time

def worker(lock):
    print(f"Process {multiprocessing.current_process().name} is doing some work before acquiring the lock.")
    # 模拟一些不受锁影响的操作
    time.sleep(2)
    print(f"Process {multiprocessing.current_process().name} is trying to acquire the lock.")
    lock.acquire()
    print(f"Process {multiprocessing.current_process().name} has acquired the lock.")
    # 模拟长时间操作，并且不释放锁
    time.sleep(100)

if __name__ == "__main__":
    lock = multiprocessing.Lock()
    p1 = multiprocessing.Process(target=worker, args=(lock,))
    p2 = multiprocessing.Process(target=worker, args=(lock,))

    p1.start()
    p2.start()

    p1.join()
    p2.join()